import React, { useEffect, useState } from "react";
import { Button, Modal, Upload, message } from "antd";
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { fileUpload } from "@/services/common";
import { UploadOutlined } from "@ant-design/icons";
import { checkFileSize, getFileNameByPath } from '@/utils/util';

const XlUpload = ({ 
  value,
  onChange,
  max = 1,
  maxSize=20,
  uploadParams = {},
  uploadButton = (
    <div style={{border: '1px solid #dbdbdb', borderRadius: '5px', width: 100, height: 100, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', cursor: 'pointer'}}>
      <UploadOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  ),
  ...props
}: any) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };
  const handleChange = ({ file }: any) => {
    if (file.status === 'removed') {
      const index = fileList.findIndex((item) => item.uid === file.uid);
      const list = [...fileList];
      list.splice(index, 1);
      setFileList(list);
      onChange(list);
    }
  };
  const handleCancel = () => setPreviewOpen(false);

  const handleCustomRequest = (file: any) => {
    const formData = new FormData();
    formData.append('file', file.file);
    if (uploadParams) {
      Object.keys(uploadParams).forEach(key => {
        formData.append(key, uploadParams[key]);
      })
    }
    fileUpload(formData).then((response) => {
      if (response?.code === '0') {
        const arr = [
          ...fileList,
          { originFileObj: file.file, uid: response.data, name: getFileNameByPath(response?.data), responseUrl: response?.data },
        ];
        setFileList(arr);
        onChange(arr);
        file?.onSuccess();
      } else {
        file?.onError();
      }
    });
  };

  const uploadProps: UploadProps = {
    ...props,
    beforeUpload: ({ name }: any, [file]: any) => {
      const result = checkFileSize(file, maxSize);
      if (!result) {
        message.error('上传文件过大,请重新选择文件上传');
        return Promise.reject();
      }
      const fileType = props?.accept ? props?.accept?.split(',') : props?.accept;
      if (!fileType) {
        return Promise.resolve(true);
      }
      const fileExt = name.substr(name.lastIndexOf('.'));
      if (!fileType?.includes(fileExt.toLocaleLowerCase())) {
        message.error('请上传规定范围内的文件类型');
        return Promise.reject();
      }
      return Promise.resolve(true);
    },
    customRequest: handleCustomRequest,
    onChange: handleChange,
    onPreview: handlePreview
  };

  useEffect(() => {
    if (value?.length > 0) {
      setFileList(value?.map((v: any) => ({
        ...v,
        uid: v?.path,
        isDefault: true,
        status: 'done',
      })));
    } else {
      setFileList([]);
    }
  }, [JSON.stringify(value)])

  return (
    <>
      <Upload {...uploadProps} fileList={fileList}>
        {fileList.length >= max ? null : uploadButton}
      </Upload>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
}

export default XlUpload;